package com.yang.job.admin.infra.job.thread;

import com.alibaba.fastjson.JSONObject;
import com.yang.job.admin.domain.valueobject.RemoteExecutorMessage;
import com.yang.job.core.dto.YangJobTransferDTO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class RemoteJobExecuteThread implements Runnable {
    private YangJobTransferDTO yangJobTransferDTO;

    private RemoteExecutorMessage remoteExecutorMessage;

    public RemoteJobExecuteThread(RemoteExecutorMessage remoteExecutorMessage, YangJobTransferDTO yangJobTransferDTO) {
        this.remoteExecutorMessage = remoteExecutorMessage;
        this.yangJobTransferDTO = yangJobTransferDTO;
    }

    @Override
    public void run() {
        try {
            String ip = remoteExecutorMessage.getIp();
            Integer port = remoteExecutorMessage.getPort();
            Socket socket = new Socket(ip, port);
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            printWriter.println(JSONObject.toJSONString(yangJobTransferDTO));

            bufferedReader.close();
            printWriter.close();
            socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
